const axios = require('axios')
const {
  JPUSH_APP_KEY,
  JPUSH_MASTER_SECRET,
  JPUSH_APP_KEY_PROVIDER,
  JPUSH_MASTER_SECRET_PROVIDER,
} = require('../../config')

// https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/

const sendUserPush = async ({
  userId,
  message, // string
  extras = {}, // json object
}) => {
  try {
    const alias = [].concat(userId).map(item => `${item}`)
    const accessToken = Buffer.from(`${JPUSH_APP_KEY}:${JPUSH_MASTER_SECRET}`).toString('base64')
    const headers = {
      'Content-Type': 'application/json',
      Authorization: `Basic ${accessToken}`,
    }
    const devParams = {
      platform: 'ios',
      audience: { alias },
      notification: {
        ios: {
          alert: message,
          sound: 'default',
          badge: '+1',
          extras,
        },
      },
      options: { apns_production: false },
    }
    const prodParams = {
      platform: 'all',
      audience: { alias },
      notification: {
        android: { alert: message, extras },
        ios: {
          alert: message,
          sound: 'default',
          badge: '+1',
          extras,
        },
      },
      options: { apns_production: true },
    }
    await axios.post('https://api.jpush.cn/v3/push', devParams, { headers })
    await axios.post('https://api.jpush.cn/v3/push', prodParams, { headers })
  } catch (error) {
    console.log(error)
  }
}

const sendMerchantPush = async ({
  merchantId,
  message, // string
  extras = {}, // json object
}) => {
  try {
    const alias = [].concat(merchantId).map(item => `${item}`)
    const accessToken = Buffer.from(`${JPUSH_APP_KEY_PROVIDER}:${JPUSH_MASTER_SECRET_PROVIDER}`).toString('base64')
    const headers = {
      'Content-Type': 'application/json',
      Authorization: `Basic ${accessToken}`,
    }
    const devParams = {
      platform: 'ios',
      audience: { alias },
      notification: {
        ios: {
          alert: message,
          sound: 'default',
          badge: '+1',
          extras,
        },
      },
      options: { apns_production: false },
    }
    const prodParams = {
      platform: 'all',
      audience: { alias },
      notification: {
        android: { alert: message, extras },
        ios: {
          alert: message,
          sound: 'default',
          badge: '+1',
          extras,
        },
      },
      options: { apns_production: true },
    }
    await axios.post('https://api.jpush.cn/v3/push', devParams, { headers })
    await axios.post('https://api.jpush.cn/v3/push', prodParams, { headers })
  } catch (error) {
    console.log(error)
  }
  // .then((response) => {
  //   console.log(response.data)
  // }).catch((error) => {
  //   console.log(error)
  // })
}

module.exports = {
  sendUserPush,
  sendMerchantPush,
}
